<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <script src="/js/rem.js" type="text/javascript"></script>
    <title>上传图片作品</title>
    <link rel="stylesheet" href="/css/common.css" type="text/css">
    <link rel="stylesheet" href="/css/sign-up.css" type="text/css">
</head>
<body>
<div id="signup_main" class="active">
    <div class="content">
        <form method="post" action="" id="upload_video_form">
            <input type="hidden" th:value="${work_info.getACTIVITY_ID()}" name="activity_id">
            <input type="hidden" th:value="${work_info.getUSER_ID()}" name="user_id">
            <input type="hidden" th:value="${work_info.getWORK_ID()}" name="work_id">
            <input type="hidden" th:value="${is_back}" id="is_back">
            <input type="hidden" name="RESOURCE_URL" id="RESOURCE_URL">
            <div class="workname">
                <label>作品名称</label>
                <input name="work_name" th:value="${work_info.getWORK_NAME()}" type="text" placeholder="请输入您的作品名称"/>
            </div>
            <div class="video1">
                <label>请上传封面</label>
                <input th:value="${work_info.getWORK_IMGURL()}" class="img_input" type="hidden" name="work_imgurl">
                <div class="video_button img_div">
                   <span>
                      <img src="/img/add.png"><br>
                      <span>请选择PNG、JPEG、GIF等格式</span>
                   </span>
                </div>
                <span style="color: red;font-size: 0.8rem">上传文件不得超过100M！</span>
            </div>
            <div class="video1">
                <label>请上传图片文件</label>
                <div class="video_btn" id="add_pic">添加</div>
                <div class="layui-input-block" id="pic_list" style="margin-top: 15px;">


                    <div class="video1 pic_item"   th:each="urlmap:${work_info.getURL()}"   >
                        <input type="hidden" class="img_input" th:value="${urlmap.url}" name="RESOURCE_URL">
                        <div class="video_button img_div" th:style="${'background-image:url('+urlmap.url+');'}"  >
                            <span style="display: none">
                              <img src="/img/add.png"><br>
                              <span>请选择PNG、JPEG、GIF等格式</span>
                           </span>
                        </div>
                        <a class="delete_item" style="color:red;">删除</a>
                    </div>

                </div>
            </div>
            <div  class="workname">
                <label>作品描述（200字以内）</label><br>
                <textarea name="work_assessment" style="min-height:140px;width: 100%; margin-top: 10px;    font-size: 16px;  padding: 4px; box-sizing: border-box;" placeholder="请输入您的作品描述">[[${work_info.getWORK_ASSESSMENT()}]]</textarea>
            </div>
            <div class="sign_up">
                <button type="button" id="button_signup"><span></span></button>
            </div>
        </form>
    </div>
</div>
<script type="text/html" id="pic_name_item">
    <div class="video1 pic_item">
        <input type="hidden" class="img_input" name="RESOURCE_URL">
        <div class="video_button img_div">
            <span>
              <img src="/img/add.png"><br>
              <span>请选择PNG、JPEG、GIF等格式</span>
           </span>
        </div>
        <a class="delete_item" style="color:red;">删除</a>
    </div>
</script>
<script type="text/javascript" src="/js/zepto.js"></script>
<script type="text/javascript" src="/js/touch.js"></script>
<script type="text/javascript" src="/js/util.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script type="text/javascript">


    var URL=window.location.href.split("#")[0];
    $.ajax({
        async : false,   //这里参数true和false在微信中打开会有不同效果，实际用的时候用false,用true时候测试会有提示性内容。
        url : '/share',
        type : "POST",
        dataType : "json", // 返回的数据类型，设置为JSONP方式
        data : {
            URL : encodeURIComponent(URL)
        },
        success: function(response, status, xhr){
            //console.log('状态为：' + status + ',状态是：' + xhr.statusText);
            //console.log(response);
            wx.config({
                debug: false, //调试阶段建议开启，关闭就不弹提示了
                appId: response.appId,//APPID
                timestamp: response.timestamp,//上面main方法中拿到的时间戳timestamp
                nonceStr: response.nonceStr,//上面main方法中拿到的随机数nonceStr
                signature: response.signature,//上面main方法中拿到的签名signature
                //需要调用的方法接口
                jsApiList: ['chooseImage', 'uploadImage', 'downloadImage']
            });
            wx.error(function(res){
                //alert("微信JsSDK配置错误，部分功能可能无法使用！")
                console.log(res);
            });
            wx.ready(function(){
                console.log("微信JsSDK配置完成");

            });
        },
        error:function(reason){
            alert("网络错误，未能初始化微信JS-SDK.")
        }
    });






</script>
<script type="text/javascript">
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }
    $(function () {
        var img = $("input[name='work_imgurl']");

        console.log(img.val())
        if (img.val()) {
            img.siblings(".img_div").css("background-image", "url(" + img.val() + ")");
            img.siblings(".img_div").children("span").hide();
        }
    })
    //添加条目
    $("#add_pic").click(function (event) {//添加图片
        var s = $("#pic_list").children().length;
        if (s < 9) {
            $("#pic_list").append($("#pic_name_item").html());
        } else {
            alert("最多支持添加9张图片！")
        }
        return false;
    });


    //监听图片添加
    $(".content").on("tap", ".img_div", function (a, b) {
        // alert("添加图片");
        var that = this;
        //加载图片
        LoadLocalImage(function (localdata) {
            $(that).css("background-image", "url(" + localdata + ")");
        }, function (serverdata) {
            $(that).children("span").hide();
            $(that).siblings("input.img_input").val(serverdata);
        });

    })
    //监听删除
    $(".content").on("click", ".delete_item", function () {
        $(this).parent(".pic_item").remove();
        return false;
    })

    function LoadLocalImage(local_success, server_success) {
        // console.log(img)
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log("选择的图片结果为：", res);
                var localId = res.localIds[0]; // 返回选定照片的本地 ID 列表，localId可以作为 img 标签的 src 属性显示图片
                //显示加载
                showLoading();
                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                    wx.getLocalImgData({
                        localId: localId, // 图片的localID
                        success: function (res) {
                            var localData = res.localData; // localData是图片的base64数据，可以用 img 标签显示
                            if (local_success) local_success(localData);
                            closeLoading();

                        }
                    });
                } else {
                    if (local_success) local_success(localId);
                }

                wx.uploadImage({
                    localId: localId, // 需要上传的图片的本地ID，由 chooseImage 接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        if (server_success) server_success(serverId);

                        //关闭加载
                        closeLoading();
                    }
                });


            }
        });


    }


    $("#button_signup").on("tap", function (evt) {
        var img_arr = [];
        $("#pic_list").find("input[name='RESOURCE_URL']").each(function (index, item) {
            if ($(this).val()) {

                img_arr.push($(this).val())
            }
        });

        var data = $("#upload_video_form").serializeObject();

        if (!data.work_name) {
            alert("请填写作品名称！")
            return;
        }
        if (!data.work_imgurl) {
                alert("请为作品添加个封面")
            return;
        }
        if(img_arr.length<=0){
            alert("请至少上传一张图片！")
            return;

        }
        if (data.work_assessment.length > 200) {
            alert('作品描述最多写入200个字符')
            return;
        }
        var formData = new FormData();
        formData.append("ACTIVITY_ID", data.activity_id);
        formData.append("USER_ID", data.user_id);
        formData.append("WORK_ID", data.work_id);
        formData.append("WORK_NAME", data.work_name);
        formData.append("WORK_ASSESSMENT", data.work_assessment);
        formData.append("WORK_IMGURL", data.work_imgurl);
        formData.append("RESOURCE_URL", img_arr.join(","));
        $("#button_signup>span").addClass("loading");
        window.showLoading();
        $.ajax({
            type: "post",
            url: "/front/uploadPic",
            async: true,
            processData: false,
            contentType: false,
            data: formData,
            dataType: "json",
            success: function (res) {
                console.log(res)
                if (res.code == "1") {
                    alert("提交成功")
                    //返回上一级

                    sessionStorage.setItem("need_refresh",true);

                    window.history.back();

                } else if (res.code == "-1") {
                    alert(res.msg)
                }
                else {
                    alert("服务器返回了错误的结果！")
                }
            },
            error: function (res) {
                alert("网络错误。")
            },
            complete: function () {
                $("#button_signup>span").removeClass("loading");
                window.closeLoading();
            }
        })
        return false;
    })
</script>
</body>
</html>
